import { _decorator, Component, Node, Collider, ITriggerEvent } from 'cc'
import { GameManager } from '../framework/GameManager'
const { ccclass, property } = _decorator

const SCOPED = 60
@ccclass('BulletProp')
export class BulletProp extends Component {
  propSpeedX = 0.3 // 道具X轴移动速度
  propSpeedZ = 0.3 // 道具Z轴移动速度

  maxScopedL = -20 // 最大左边距
  maxScopedR = 20 // 最大右边距

  gameManager: GameManager = null // 游戏节点

  direction = 'right' // x轴移动方向

  update(deltaTime: number) {
    this.bulletMove(deltaTime)
  }

  onEnable() {
    // 获取碰撞组件
    const collider = this.getComponent(Collider)
    // 监听开始碰撞
    collider.on('onTriggerEnter', this.onTriggerEnter, this)
  }

  onDisable() {
    const collider = this.getComponent(Collider)
    collider.off('onTriggerEnter', this.onTriggerEnter, this)
  }

  // 碰撞处理
  onTriggerEnter(event: ITriggerEvent) {
    const propName = event.selfCollider.node.name
    switch (propName) {
      case 'bulletH': // H子弹
        this.gameManager.setBulletData(2)
        break
      case 'bulletS': // S子弹
        this.gameManager.setBulletData(3)
        break
      default: // M子弹
        this.gameManager.setBulletData(5)
        break
    }

    this.node.destroy()
  }

  // 道具移动
  bulletMove(deltaTime: number) {
    const pos = this.node.position
    const xMove = this.direction === 'right' ? pos.x + this.propSpeedX : pos.x - this.propSpeedX
    if (xMove > this.maxScopedR) {
      this.direction = 'left'
    }
    if (xMove < this.maxScopedL) {
      this.direction = 'right'
    }
    const zMove = pos.z + this.propSpeedZ
    this.node.setPosition(xMove, pos.y, zMove)
    if (zMove > SCOPED) {
      this.node.destroy()
    }
  }

  // 参数1 gameManager节点
  // 参数2 道具X轴移动速度
  // 参数3 道具Z轴移动速度
  set(gameManager: GameManager, propSpeedX: number = 0.3, propSpeedZ: number = 0.3) {
    this.gameManager = gameManager
    this.propSpeedX = propSpeedX
    this.propSpeedZ = propSpeedZ
  }
}
